package com.atguigu.window;

import com.atguigu.bean.WaterSensor;
import com.atguigu.function.WaterSensorMapFunction;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

public class WindowAggregateAndProcessDemo {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);


        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .socketTextStream("10.75.186.206", 9999)
                .map(new WaterSensorMapFunction());

//        sensorDS.wi

        KeyedStream<WaterSensor, String> waterSensorStringKeyedStream = sensorDS.keyBy(w -> w.getId());

        WindowedStream<WaterSensor, String, TimeWindow> window = waterSensorStringKeyedStream.window(TumblingProcessingTimeWindows.of(Time.seconds(10)));

        SingleOutputStreamOperator<String> result = window.aggregate(
                new MyAggregate(),
                new MyWindowFunction());

        result.print();

        env.execute();
    }

    static class MyAggregate implements AggregateFunction<WaterSensor, Integer, String> {
        /**
         * 创建累加器，初始化累加器
         * @return
         */
        @Override
        public Integer createAccumulator() {
            System.out.println("创建新窗口，初始化值为0");
            return 0;
        }

        /**
         * 聚合逻辑
         * @param waterSensor
         * @param integer
         * @return
         */
        @Override
        public Integer add(WaterSensor waterSensor, Integer integer) {
            System.out.println("调用add方法，w1:" + waterSensor.getVc() + "w2:" + integer);
            return waterSensor.getVc() + integer;
        }

        /**
         * 获取最终结果，窗口触发时输出
         * @param integer
         * @return
         */
        @Override
        public String getResult(Integer integer) {
            System.out.println("获取结果");
            return integer.toString();
        }

        @Override
        public Integer merge(Integer integer, Integer acc1) {
            // 只有会话窗口才会用到
            return null;
        }
    }

    static class MyWindowFunction extends ProcessWindowFunction<String, String, String, TimeWindow> {

        @Override
        public void process(String key, ProcessWindowFunction<String, String, String, TimeWindow>.Context context, Iterable<String> elements, Collector<String> out) throws Exception {
            long start = context.window().getStart();
            long end = context.window().getEnd();
            String windowStart = DateFormatUtils.format(start, "yyyy-MM-dd HH:mm:ss.SSS");
            String windowEnd = DateFormatUtils.format(end, "yyyy-MM-dd HH:mm:ss.SSS");
            long count = elements.spliterator().estimateSize();
            out.collect("key=" + key + "的窗口[" + windowStart + "," + windowEnd + ")包含" + count + "条数据===>" + elements.toString());
        }
    }

}
